package com.yiqi.liebang.feature.home.view;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.suozhang.framework.component.recyclerview.DividerItemDecoration;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.T;
import com.suozhang.framework.widget.EmptyView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.yiqi.liebang.R;
import com.yiqi.liebang.common.rongim.bean.ShareQuestionBean;
import com.yiqi.liebang.common.rongim.msg.QuestionMessage;
import com.yiqi.liebang.common.widget.RatingBar;
import com.yiqi.liebang.common.widget.ShareBottomDialog;
import com.yiqi.liebang.common.widget.dialog.BaseAnimatorSet;
import com.yiqi.liebang.common.widget.dialog.BounceTopEnter;
import com.yiqi.liebang.entity.bo.OrderQuestionInfofBo;
import com.yiqi.liebang.entity.bo.QuestionDetailBo;
import com.yiqi.liebang.feature.home.view.adapter.QuestionRecommendAdapter;
import com.yiqi.liebang.feature.mine.view.UserInfoActivity;
import com.yiqi.liebang.feature.order.contract.QuestionInfoContract;
import com.yiqi.liebang.feature.order.dependencies.questionInfo.DaggerQuestionInfoComponent;
import com.yiqi.liebang.feature.order.dependencies.questionInfo.QuestionInfoPresenterModule;
import com.yiqi.liebang.feature.people.view.FriendsListActivity;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.rongcloud.contactcard.Friend;
import io.rong.imkit.RongIM;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;

import static com.yiqi.liebang.feature.order.view.adapter.QuestionAdapter.getDatePoor;

public class AskInfoActivity extends BaseActivity implements QuestionInfoContract.View,
        Toolbar.OnMenuItemClickListener,
        RadioGroup.OnCheckedChangeListener, View.OnClickListener {
    @Inject
    QuestionInfoContract.Presenter mPresenter;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.tv_ask_info_sign)
    TextView mTvAskInfoSign;
    @BindView(R.id.tv_question_info_content)
    TextView mTvQuestionInfoContent;
    @BindView(R.id.iv_question_info_head)
    ImageView mIvQuestionInfoHead;
    @BindView(R.id.tv_order_question_name)
    TextView mTvOrderQuestionName;
    @BindView(R.id.iv_question_info_position)
    TextView mIvQuestionInfoPosition;
    @BindView(R.id.iv_user_position)
    ImageView mIvUserPosition;
    @BindView(R.id.iv_question_info_help)
    TextView mIvQuestionInfoHelp;
    @BindView(R.id.star_question_info)
    RatingBar mStarQuestionInfo;
    @BindView(R.id.btn_question_info_ask)
    TextView mBtnQuestionInfoAsk;
    @BindView(R.id.tv_question_info_shixiao)
    TextView mTvQuestionInfoShixiao;
    @BindView(R.id.type_question_had_pay)
    LinearLayout mTypeQuestionHadPay;
    @BindView(R.id.type_question_had_expired)
    LinearLayout mTypeQuestionHadExpired;
    @BindView(R.id.type_question_had_fefused)
    LinearLayout mTypeQuestionHadFefused;
    @BindView(R.id.tv_question_expert_shixiao)
    TextView mTvQuestionExpertShixiao;
    @BindView(R.id.type_question_validate_expert)
    LinearLayout mTypeQuestionValidateExpert;
    @BindView(R.id.view_expert_info)
    LinearLayout mViewExpertInfo;
    @BindView(R.id.rgp_topic_type)
    RadioGroup mRgpTopicType;
    @BindView(R.id.edt_answer_content)
    EditText mEdtAnswerContent;
    @BindView(R.id.type_question_answer_expert)
    LinearLayout mTypeQuestionAnswerExpert;
    @BindView(R.id.type_question_ignore_expert)
    LinearLayout mTypeQuestionIgnoreExpert;


    @BindView(R.id.view_question_info)
    LinearLayout mViewQuestionInfo;


    @BindView(R.id.rb_queestion_comment_star)
    RatingBar mRbQueestionCommentStar;
    @BindView(R.id.tv_show_star)
    TextView mTvShowStar;
    @BindView(R.id.btn_confrim_comment)
    TextView mBtnConfrimComment;
    @BindView(R.id.rb_user_question_star)
    RatingBar mRbUserQuestionStar;
    @BindView(R.id.view_to_comment)
    LinearLayout mViewToComment;
    @BindView(R.id.iv_user_certification)
    ImageView mIvUserCertification;
    @BindView(R.id.tv_expert_title)
    TextView mTvExpertTitle;
    @BindView(R.id.tv_show_count)
    TextView mTvShowCount;
    @BindView(R.id.view_count)
    LinearLayout mViewCount;


    ShareBottomDialog mShareDialog;
    @BindView(R.id.rv_question_recommend)
    RecyclerView mRvQuestionRecommend;
    @BindView(R.id.view_question_recommend)
    LinearLayout mViewQuestionRecommend;
    @BindView(R.id.view_question_view)
    LinearLayout mViewQuestionView;
    @BindView(R.id.tv_answer_content)
    TextView tvAnswerContent;
    @BindView(R.id.view_xgwd)
    LinearLayout viewXgwd;
    @BindView(R.id.btn_zhankai_all)
    TextView mBtnZhankaiAll;
    Boolean flag = true;

    private int mAnswerType = 1;
    OrderQuestionInfofBo mData;
    private EmptyView mEmptyView;
    private float mScore;
    private String mAnswerId;
    private boolean isExpert = false;


    UMImage image;//网络图片
    UMWeb umWeb;
    private QuestionRecommendAdapter mAdapter;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_ask_info;
    }

    @Override
    protected void initInjector() {
        DaggerQuestionInfoComponent.builder().questionInfoPresenterModule(new QuestionInfoPresenterModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {
        isExpert = this.getIntent().getBooleanExtra("is_expert", false);
        mToolbar.setOnMenuItemClickListener(this);
        initToolBar(mToolbar, "问答详情", true, true);


    }

    @Override
    protected void initData() {
        mAnswerId = this.getIntent().getStringExtra("order_id");
//        mAnswerId = this.getIntent().getStringExtra("answer_id");
        mPresenter.getOrderQuestionInfo(mAnswerId, isExpert ? 4 : 1);


    }

    @Override
    protected void initEvent() {
        mRgpTopicType.setOnCheckedChangeListener(this);
    }

    @Override
    public void showOrderQuestionInfoSuccess(OrderQuestionInfofBo data) {
        mData = data;

        image = new UMImage(this, data.getQuestionFormMap().getQuestionUserAccount().getUserHead());
        umWeb = new UMWeb("http://liebangapp.com/yindao/");
        umWeb.setTitle(data.getQuestionFormMap().getQuizcontent());//标题
        umWeb.setThumb(image);  //缩略图
        umWeb.setDescription(data.getQuestionFormMap().getAnswerContent());//描述

        if (data.getOrderStates() == 2 || data.getOrderStates() == 3 || data.getOrderStates() == 4) {
            //显示查看人数
            mViewQuestionView.setVisibility(View.VISIBLE);
            mViewQuestionRecommend.setVisibility(View.VISIBLE);
            mTvShowCount.setText(data.getViewNum()>0 ?data.getViewNum() + "人查看":"");
            tvAnswerContent.setText(data.getQuestionFormMap().getAnswerContent());
            mRbUserQuestionStar.setStar(data.getQuestionFormMap().getStartLevel());
            mViewCount.removeAllViews();
            if (data.getViewUser() != null) {
                for (int i = 0; i < data.getViewUser().size(); i++) {
                    ImageView imageView = new ImageView(this);
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(98, 98);
                    layoutParams.setMargins(15, 0, 0, 0);
                    imageView.setLayoutParams(layoutParams);
                    AM.image().bindToCircleObject(data.getViewUser().get(i).getUserHead(), imageView);
                    mViewCount.addView(imageView);
                }
            }
            //显示相关问答
            initsAdapter(data.getQuestion());
            viewXgwd.setVisibility(isExpert ? View.GONE : View.VISIBLE);


        }

        try {
            AM.image().bindToCircleObject(data.getQuestionFormMap().getQuestionUserAccount().getUserHead(), mIvQuestionInfoHead);

            mTvOrderQuestionName.setText(data.getQuestionFormMap().getQuestionUserAccount().getUserName());
            mIvQuestionInfoPosition.setText(data.getQuestionFormMap().getQuestionUserAccount().getPosition());
            mIvQuestionInfoHelp.setText("帮助过" + data.getQuestionFormMap().getQuestionUserAccount().getHelpNum() + "人");
            mTvQuestionInfoShixiao.setText(getDatePoor(data.getQuestionFormMap().getEndTime(), System.currentTimeMillis()));
            mStarQuestionInfo.setStar(data.getQuestionFormMap().getStartLevel());

            if (data.getQuestionFormMap().getQuestionUserAccount() == null ? false : data.getQuestionFormMap().getQuestionUserAccount().getIsBasic() == 1) {
                mIvUserCertification.setVisibility(View.VISIBLE);
            } else {
                mIvUserCertification.setVisibility(View.GONE);
            }

            mTvQuestionInfoContent.setText(data.getQuestionFormMap().getQuizcontent());
            mTvQuestionInfoContent.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                @Override
                public boolean onPreDraw() {
                    int lineCount = mTvQuestionInfoContent.getLineCount();
                    if (lineCount > 3) {
                        mTvQuestionInfoContent.setLines(3);
                        mBtnZhankaiAll.setVisibility(View.VISIBLE);
                    } else {
                        mBtnZhankaiAll.setVisibility(View.GONE);
                    }
                    mBtnZhankaiAll.getViewTreeObserver().removeOnPreDrawListener(this);
                    return false;
                }
            });
            mBtnZhankaiAll.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (flag) {
                        flag = false;
                        mTvQuestionInfoContent.setEllipsize(null); // 展开
                        mTvQuestionInfoContent.setSingleLine(flag);
                        mBtnZhankaiAll.setText("收起全部");
                    } else {
                        flag = true;
                        mTvQuestionInfoContent.setEllipsize(TextUtils.TruncateAt.END); // 收缩
                        mTvQuestionInfoContent.setMaxLines(3);
                        mBtnZhankaiAll.setText("展开全部");
                    }
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
        switch (data.getOrderStates()) {
            case 0://未支付
                break;
            case 1://已支付
                mViewToComment.setVisibility(View.GONE);
                if (isExpert) {
                    mToolbar.inflateMenu(R.menu.menu_askinfo_hulue);
                    mTypeQuestionValidateExpert.setVisibility(View.VISIBLE);
                    mTvQuestionExpertShixiao.setText(getDatePoor(data.getQuestionFormMap().getEndTime(), System.currentTimeMillis()));
                    mBtnQuestionInfoAsk.setText("回答");
                } else {
                    mTypeQuestionHadPay.setVisibility(View.VISIBLE);
                }

                break;
            case 2://已作答
                mToolbar.inflateMenu(R.menu.menu_share);
                mViewExpertInfo.setVisibility(View.VISIBLE);

                if (isExpert) {
                    mBtnQuestionInfoAsk.setVisibility(View.GONE);
                    mViewToComment.setVisibility(View.GONE);
                } else {
                    mViewToComment.setVisibility(View.VISIBLE);
                    mRbQueestionCommentStar.setOnRatingChangeListener(new RatingBar.OnRatingChangeListener() {
                        @Override
                        public void onRatingChange(float ratingCount) {
                            mScore = ratingCount;
                            if (ratingCount > 0) {
                                mTvShowStar.setVisibility(View.VISIBLE);
                                mBtnConfrimComment.setVisibility(View.VISIBLE);
                            } else {
                                mTvShowStar.setVisibility(View.GONE);
                                mBtnConfrimComment.setVisibility(View.GONE);
                            }
                            if (ratingCount == 1) {
                                mTvShowStar.setText("非常不满意");
                            } else if (ratingCount == 2) {
                                mTvShowStar.setText("不满意");
                            } else if (ratingCount == 3) {
                                mTvShowStar.setText("一般般");
                            } else if (ratingCount == 4) {
                                mTvShowStar.setText("较满意");
                            } else if (ratingCount == 5) {
                                mTvShowStar.setText("非常满意");
                            }
                        }
                    });
                }
                break;
            case 3://已评价
                if (isExpert) {
                    mBtnQuestionInfoAsk.setVisibility(View.GONE);
                } else {
                    mBtnQuestionInfoAsk.setVisibility(View.VISIBLE);
                }

                mToolbar.inflateMenu(R.menu.menu_share);

//                mTypeQuestionHadReply.setVisibility(View.VISIBLE);

                mViewToComment.setVisibility(View.GONE);

                break;
            case 4: //已确认

                mBtnQuestionInfoAsk.setVisibility(View.GONE);
                mToolbar.inflateMenu(R.menu.menu_share);

//                mTypeQuestionHadReply.setVisibility(View.VISIBLE);

                mViewToComment.setVisibility(View.GONE);
                break;
            case 5://已取消
                if (isExpert) {
                    mBtnQuestionInfoAsk.setVisibility(View.GONE);
                }
                break;
            case 6://已忽略
                if (isExpert) {
                    mBtnQuestionInfoAsk.setVisibility(View.GONE);
                    mTypeQuestionIgnoreExpert.setVisibility(View.VISIBLE);
                } else {
                    mTypeQuestionHadFefused.setVisibility(View.VISIBLE);
                }
                break;
            case 7://已失效
                if (isExpert) {
                    mBtnQuestionInfoAsk.setVisibility(View.GONE);
                }

                mTypeQuestionHadExpired.setVisibility(View.VISIBLE);
                break;
            case 8://已退款
                if (isExpert) {
                    mBtnQuestionInfoAsk.setVisibility(View.GONE);
                    mTypeQuestionIgnoreExpert.setVisibility(View.VISIBLE);
                    mTvExpertTitle.setText("没有在48小时内回答问题");
                    mBtnQuestionInfoAsk.setVisibility(View.GONE);
                } else {
                    mTypeQuestionHadExpired.setVisibility(View.VISIBLE);
                }

                break;

        }

    }

    public void initsAdapter(List<QuestionDetailBo.QuestionBean> questionBeans) {
        mEmptyView = new EmptyView(mRvQuestionRecommend);
        mRvQuestionRecommend.setLayoutManager(new LinearLayoutManager(this));
        mRvQuestionRecommend.addItemDecoration(new DividerItemDecoration(DividerItemDecoration.VERTICAL).setHeight(2));
        mAdapter = new QuestionRecommendAdapter();
        mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT);
        mAdapter.bindToRecyclerView(mRvQuestionRecommend);
        if (questionBeans != null && questionBeans.size() > 0) {
            mAdapter.setNewData(questionBeans);
        } else {
            mAdapter.setEmptyView(mEmptyView.getEmptyView("暂无相关问答"));
            mAdapter.setNewData(null);
        }

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(AskInfoActivity.this, AskDetailActivity.class);
                intent.putExtra("answer_id", mData.getQuestion().get(position).getId());
                startActivity(intent);
            }
        });
    }

    @Override
    public void showOrderQuestionDetailSuccess(QuestionDetailBo infofBo) {

    }


    @Override
    public void showRefusedQuestion(String s) {
        showMsg("忽略成功！");
        finish();
    }

    @Override
    public void showAnswerSuccess(String s) {
        showMsg("回答成功！");
        finish();
    }

    @Override
    public void showCommentSuccess(String s) {
        showMsg("评价成功！");
        finish();
    }


    @Override
    public void showOrderQuestionInfoError(String error) {
        showErrorMsg(error);
    }

    @Override
    public void showCommentDetailSuccess(String s) {

    }


    @SuppressLint("RestrictedApi")
    @OnClick({R.id.btn_question_info_ask, R.id.btn_confrim_answer, R.id.btn_confrim_comment, R.id.iv_question_info_head, R.id.btn_user_tiwen})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_question_info_ask:
                if (isExpert) {
                    mToolbar.getMenu().clear();
                    mToolbar.inflateMenu(R.menu.menu_save);
                    initToolBar(mToolbar, "问答详情", true, true);
                    mViewExpertInfo.setVisibility(View.GONE);
                    mTypeQuestionValidateExpert.setVisibility(View.GONE);
                    mTypeQuestionAnswerExpert.setVisibility(View.VISIBLE);
                } else {
                    Intent intentAsk = new Intent(this, AskActivity.class);
                    intentAsk.putExtra("user_id", mData.getQuestionFormMap().getQuestionUserAccount().getUserUid());
                    startActivity(intentAsk);
                }
                break;
            case R.id.btn_confrim_answer:
                mPresenter.toAnswer(mAnswerId, mEdtAnswerContent.getText().toString(), mAnswerType);
                break;
            case R.id.btn_confrim_comment:
                mPresenter.toComment(mAnswerId, mScore);
                break;
            case R.id.iv_question_info_head:
                Intent intent = new Intent(this, UserInfoActivity.class);
                intent.putExtra("is_view_my", false);
                intent.putExtra("visitorUid", mData.getQuestionFormMap().getQuestionUserAccount().getUserUid());
                startActivity(intent);
                break;
            case R.id.btn_user_tiwen:
                startActivity(new Intent(this, AskActivity.class));
                break;
        }
    }


    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_hulue:
                mPresenter.refusedQuestion(mAnswerId);
                break;
            case R.id.action_next:
                mPresenter.toAnswer(mAnswerId, mEdtAnswerContent.getText().toString(), mAnswerType);
                break;
            case R.id.action_share:
                BaseAnimatorSet mBasIn = new BounceTopEnter();
                mShareDialog = new ShareBottomDialog(this, null, false);
                mShareDialog.showAnim(mBasIn)
                        .show();
                mShareDialog.setWxCircleClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new ShareAction(AskInfoActivity.this)
                                .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)//传入平台
                                .withMedia(umWeb)
                                .setCallback(shareListener)//回调监听器
                                .share();
                    }
                });
                mShareDialog.setWxClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new ShareAction(AskInfoActivity.this)
                                .setPlatform(SHARE_MEDIA.WEIXIN)//传入平台
                                .withMedia(umWeb)
                                .setCallback(shareListener)//回调监听器
                                .share();
                    }
                });
                mShareDialog.setLBClickListener(this);
                break;
        }
        return false;
    }

    private UMShareListener shareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            showLoading();
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            dismissLoading();
            T.showShort("分享成功！");
            if (mShareDialog != null) mShareDialog.dismiss();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            dismissLoading();
            T.showShort("分享失败！");
            if (mShareDialog != null) mShareDialog.dismiss();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            dismissLoading();
            T.showShort("分享取消！");

        }
    };

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId == R.id.rgb_answer_1look) {
            mAnswerType = 1;
        } else {
            mAnswerType = 0;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 23) {
            if (data == null) return;
            Friend friend = data.getParcelableExtra("three");

            if (friend == null) return;
            ShareQuestionBean questionBean = new ShareQuestionBean(
                    mData.getQuestionFormMap().getQuizcontent(), friend.getUserUid(), "1", mData.getQuestionFormMap().getId() + "");
            String json = JSONObject.toJSONString(questionBean);

            QuestionMessage questionMessage = QuestionMessage.obtain("",
                    "",
                    friend.getUserUid(),
                    json,
                    mData.getQuestionFormMap().getQuestionUserAccount().getUserUid(),
                    mData.getQuestionFormMap().getQuizcontent(),
                    "1",
                    mData.getId() + ""

            );


            RongIM.getInstance().sendMessage(Message.obtain(questionBean.getShareUid(),
                    Conversation.ConversationType.PRIVATE, questionMessage), "sass", "sss",
                    new IRongCallback.ISendMessageCallback() {
                        @Override
                        public void onAttached(Message message) {

                        }

                        @Override
                        public void onSuccess(Message message) {
                            T.showShort("已发送！");
                            if (mShareDialog != null) {
                                mShareDialog.dismiss();
                            }
                            RongIM.getInstance().startConversation(AskInfoActivity.this, Conversation.ConversationType.PRIVATE, friend.getUserUid(), friend.getUserName());

                        }

                        @Override
                        public void onError(Message message, RongIMClient.ErrorCode errorCode) {
                            T.showShort("onError" + errorCode.getMessage());
                            if (mShareDialog != null) {
                                mShareDialog.dismiss();
                            }
                        }
                    });
        }
    }

    @Override
    public void onClick(View v) {

        Intent intent = new Intent(this, FriendsListActivity.class);
        intent.putExtra("is_select", true);
        startActivityForResult(intent, 23);

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}


